package com.gxa.ssm251.controller;

import com.gxa.ssm251.exception.BusinessException;
import com.gxa.ssm251.pojo.RedeemCode;
import com.gxa.ssm251.service.RedeemCodeService;
import com.gxa.ssm251.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 舒空
 * //@CrossOrigin 解决跨域
 */
@RestController
@RequestMapping("/redeemCode")
@Api(value = "兑换码控制器", tags = "兑换码接口api")
@CrossOrigin//解决跨域

public class RedeemCodeController {

    @Resource
    private RedeemCodeService redeemCodeService;

    private final JsonResult jsonResult = new JsonResult();



    @ApiOperation(value = "兑换码添加接口")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json格式的兑换码对象",
                    paramType = "body")
    )
    @PostMapping("/add")
    public JsonResult addRedeemCode(@RequestBody Map<String, Object> map) {

        RedeemCode redeemCode = new RedeemCode();
        redeemCode.setName(map.get("name").toString());
        redeemCode.setStartTime(Date.valueOf(map.get("startTime").toString()));
        redeemCode.setEndTime(Date.valueOf(map.get("endTime").toString()));
        redeemCode.setNumber(Integer.valueOf(map.get("number").toString()));
        redeemCode.setPrice(Double.valueOf(map.get("price").toString()));
        Integer integer = null;
        try {
            integer = redeemCodeService.addRedeemCode(redeemCode);
            RedeemCode selectByName = redeemCodeService.selectByName(redeemCode.getName());
            String scope = map.get("Scope").toString();
            List<String> list = new ArrayList<>();
            String[] split = scope.split(",");
            list = Arrays.asList(split);
            Integer integer1 = redeemCodeService.addRcScope(selectByName.getId(), list);
            if (integer > 0 && integer1 > 0) {
                jsonResult.setCode("1");
                jsonResult.setMsg("添加成功");
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("添加失败");
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                jsonResult.setCode("0");
                jsonResult.setMsg(e.getMessage());
            } else {
                e.printStackTrace();
            }
        }

        return jsonResult;
    }

}
